package com.df.designmode.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author dongfang
 */
public class ProxyFactory {

    private Object target;

    public ProxyFactory(Object obj) {
        this.target = obj;
    }

    /**
     * 动态代理
     */
    public Object newProxyInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    System.out.println("ProxyFactory#newProxyInstance#InvocationHandler#invokem 0");
                    Object resutl = method.invoke(target, args);
                    System.out.println("ProxyFactory#newProxyInstance#InvocationHandler#invokem 1");


                    return resutl;
                }
        );
    }

    public static void main(String[] args) {
        IUserDao targer = new UserDao();
        System.out.println("1--" + targer.getClass());

        IUserDao proxy = (IUserDao) new ProxyFactory(targer).newProxyInstance();
        System.out.println("2--" + proxy.getClass());
        targer.save();
        proxy.save();
    }
}
